package com.ylbh.modules.activity.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ylbh.common.annotation.SysLog;
import com.ylbh.common.pojo.activity.dto.*;
import com.ylbh.common.pojo.activity.vo.ShoppingActivityVO;
import com.ylbh.common.utils.*;
import com.ylbh.modules.activity.mapper.SpikeActivityMapper;
import com.ylbh.modules.activity.service.SpikeGoodsService;
import com.ylbh.modules.activity.service.SpikeActivityService;
import com.ylbh.modules.outerchain.entity.ShoppingOuterChain;
import com.ylbh.modules.outerchain.service.ShoppingOuterChainService;
import com.ylbh.modules.sys.controller.AbstractController;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 秒杀活动
 * @author mgh
 */
@RestController
@RequestMapping("activity/spike")
public class SpikeActivityController extends AbstractController {
    @Autowired
    private SpikeActivityService spikeActivityService;
    @Autowired
    private SpikeGoodsService spikeGoodsService;
    @Autowired
    private SpikeActivityMapper spikeActivityMapper;
    @Autowired
    private ShoppingOuterChainService shoppingOuterChainService;

    /**
     * 获取活动列表
     */
    @RequestMapping("/queryActivityList")
    @RequiresPermissions("spike:activity:queryActivityList")
    public CommonResult<PageUtils> list(PageDTO params){
        PageUtils page = spikeActivityService.queryActivityPage(params);

        return Ref.ok(page);
    }

    /**
     * 获取活动名列表
     */
    @RequestMapping("/getActivityNameList")
    public CommonResult<List<ShoppingActivityVO>> getActivityNameList(){
        List<ShoppingActivityVO> activityVOList =  spikeActivityService.queryActivityNameList();

        return Ref.ok(activityVOList);
    }


    /**
     * 信息
     */
    @RequestMapping("/getActivityById/{activityId}")
    @RequiresPermissions("spike:activity:getActivityById")
    public CommonResult<ShoppingActivityDTO> info(@PathVariable("activityId") String activityId){
		ShoppingActivityDTO shoppingActivity = spikeActivityService.getById(activityId);

        return Ref.ok(shoppingActivity);
    }

    /**
     * 保存
     */
    @SysLog("添加秒杀活动")
    @RequestMapping("/add/{address}")
    @RequiresPermissions("spike:activity:add")
    public CommonResult save(@RequestBody ShoppingActivityDTO shoppingActivity, @PathVariable("address") String address){
        boolean isEqual = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        shoppingActivity.setActivityId(new IdWorker().nextId());
        shoppingActivity.setActivityNo(IdWorker.getNoId().toString());
        shoppingActivity.setCreateTime(date);
        shoppingActivity.setCreateUserId(getUserId().intValue());
        shoppingActivity.setUpdateTime(date);
        shoppingActivity.setState(0);
        isEqual = sdf.format(shoppingActivity.getBeginTime()).equals(sdf.format(shoppingActivity.getEndTime()));
//        if (shoppingActivity.getBeginTime() == shoppingActivity.getEndTime())
//            isEqual = true;
        try {
            String endTime = sdf.format(shoppingActivity.getEndTime());
            shoppingActivity.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime + " 23:59:59"));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 根据活动的外链id去查询地址
        ShoppingOuterChain activityUrl = shoppingOuterChainService.getOuterChainById(Long.parseLong(shoppingActivity.getActivityUrl()));
        shoppingActivity.setActivityUrl(activityUrl.getOuterUrl() + shoppingActivity.getActivityId());
        spikeActivityService.save(shoppingActivity);

		// 同时要去整点活动表中加入对应的活动时间
        ActivityTemplateDTO templateDTO = spikeActivityService.getActivityTemplateDetails(shoppingActivity.getAtId());
        List<ActivityTimeToList> toList = FastJsonUtil.toList(templateDTO.getTimeInterval(), ActivityTimeToList.class);
        List lDate = new ArrayList();
        lDate.add(shoppingActivity.getBeginTime());
        if (!isEqual) {
            Calendar calBegin = Calendar.getInstance();
            // 使用给定的 Date 设置此 Calendar 的时间
            calBegin.setTime(shoppingActivity.getBeginTime());
            Calendar calEnd = Calendar.getInstance();
            // 使用给定的 Date 设置此 Calendar 的时间
            calEnd.setTime(shoppingActivity.getEndTime());
            // 测试此日期是否在指定日期之后
            while (shoppingActivity.getEndTime().after(calBegin.getTime())) {
                // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
                calBegin.add(Calendar.DAY_OF_MONTH, 1);
                lDate.add(calBegin.getTime());
            }
        }
        IdWorker id = new IdWorker();
        // 时间数组长度
        int length = 0;
        if (!isEqual) {
            length = lDate.size() - 1;
        } else {
            length = lDate.size();
        }
        for (int i = 0; i < length; i++) {
            for (ActivityTimeToList list:toList) {
                WholePointActivitiesDTO dto = new WholePointActivitiesDTO();
                dto.setId(id.nextId());
                dto.setActiviteTime(sdf.format(lDate.get(i)) + " 00:00:00");
                dto.setActivityStartTime(sdf.format(lDate.get(i)) + " " + list.getBeginTime() + ":00");
                dto.setActivityEndTime(sdf.format(lDate.get(i)) + " " + list.getEndTime() + ":00");
                dto.setActivityTitle(shoppingActivity.getActivityTitle());
                dto.setCreateTime(new Date());
                dto.setCreateUserId(ShiroUtils.getUserId().intValue());
                dto.setRemark(shoppingActivity.getPublishRemark());
                dto.setActivityId(shoppingActivity.getActivityId());
                spikeActivityMapper.insertWholePointActivities(dto);
            }
        }

        // 插入活动地址记录
        spikeActivityService.addActivityAddress(address, shoppingActivity.getActivityId());
        return Ref.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改秒杀活动")
    @RequestMapping("/modify")
    @RequiresPermissions("spike:activity:modify")
    public CommonResult modify(@RequestBody ShoppingActivityDTO shoppingActivity){
        // 先去查询原数据，是否对活动时间做了修改
        if (null != shoppingActivity.getBeginTime() && null != shoppingActivity.getEndTime()) {
            ShoppingActivityDTO vo = spikeActivityService.getById(shoppingActivity.getActivityId());
            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(shoppingActivity.getBeginTime());
            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(shoppingActivity.getEndTime());
            Calendar cal3 = Calendar.getInstance();
            cal3.setTime(vo.getBeginTime());
            Calendar cal4 = Calendar.getInstance();
            cal4.setTime(vo.getEndTime());
            boolean startTime = cal1.get(0) == cal3.get(0) && cal1.get(1) == cal3.get(1) && cal1.get(6) == cal3.get(6);
            boolean endTime = cal2.get(0) == cal4.get(0) && cal2.get(1) == cal4.get(1) && cal2.get(6) == cal4.get(6);
            // 如果有一个为false说明更改了时间
            if (startTime == false || endTime == false) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                List<String> updateTime = spikeActivityService.getActivityTimeDays(sdf.format(shoppingActivity.getBeginTime()), sdf.format(shoppingActivity.getEndTime()));
                List<String> originalTime = spikeActivityService.getActivityTimeDays(sdf.format(vo.getBeginTime()), sdf.format(vo.getEndTime()));
                if (updateTime.size() == originalTime.size()) {
                    // 去替换整点限时抢购时间
                    spikeActivityService.modifyWholePoint(updateTime, originalTime, shoppingActivity.getActivityId());
                } else {
                    return Ref.error("活动天数必须保持一致！");
                }
            }
        }
        shoppingActivity.setUpdateTime(new Date());
        shoppingActivity.setUpdateUserId(getUserId().intValue());

        ActivityGoodsDTO activityGoodsDTO = new ActivityGoodsDTO();
        if(shoppingActivity.getState()!=null){
            activityGoodsDTO.setActivityId(shoppingActivity.getActivityId());
            activityGoodsDTO.setState(shoppingActivity.getState().toString());
            // 修改活动状态时一起修改商品状态
            spikeGoodsService.updateStateByActivityId(activityGoodsDTO);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (null != shoppingActivity.getEndTime()) {
                String endTime = sdf.format(shoppingActivity.getEndTime());
                shoppingActivity.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime + " 23:59:59"));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        spikeActivityService.updateById(shoppingActivity);
        // 修改整点和商品上下线状态
        if (null != shoppingActivity.getState())
            spikeActivityService.modifyActivityGoodsByStateType(shoppingActivity.getState(), shoppingActivity.getActivityId());
        return Ref.ok();
    }

    /**
     * 删除
     */
    @SysLog("删除秒杀活动")
    @RequestMapping("/remove")
    @RequiresPermissions("spike:activity:remove")
    public R delete(@RequestBody String[] activityIds){
        ShoppingActivityDTO shoppingActivityDTO = new ShoppingActivityDTO();
        shoppingActivityDTO.setDeleteStatus(0);

        // 同时删除活动商品
        ActivityGoodsDTO activityGoodsDTO = new ActivityGoodsDTO();
        activityGoodsDTO.setDeleteStatus(0);

        for(String id : activityIds){
            shoppingActivityDTO.setActivityId(id);
            spikeActivityService.updateById(shoppingActivityDTO);

            activityGoodsDTO.setActivityId(id);
            spikeGoodsService.updateByActivityId(activityGoodsDTO);
        }

        return R.ok();
    }

    @SysLog("添加整点抢购时间")
    @PostMapping("addWholePointActivities")
    @ApiOperation("添加整点抢购时间")
//    @RequiresPermissions("")
    public CommonResult addWholePointActivities(@RequestBody WholePointActivitiesDTO wholePointActivitiesDTO) {
        spikeActivityService.addWholePointActivities(wholePointActivitiesDTO);
        return Ref.ok();
    }

    @GetMapping("getWholePointActivitiesTime")
    @ApiOperation("获取整点时间列表")
    public CommonResult getWholePointActivitiesTime(PageDTO pageDTO) {
        PageUtils page = spikeActivityService.getWholePointActivitiesTime(pageDTO);
        return Ref.ok(page);
    }

    @SysLog("添加整点抢购模板")
    @PostMapping("addActivityTemplate")
    @ApiOperation("添加整点抢购模板")
    @RequiresPermissions("activity:addActivityTemplate")
    public CommonResult addActivityTemplate(@RequestBody ActivityTemplateDTO activityTemplateDTO) {
        spikeActivityService.addActivityTemplate(activityTemplateDTO);
        return Ref.ok();
    }

    @GetMapping("getActivityTemplateDetails/{id}")
    @ApiOperation("获取对应抢购的模板详情")
    @RequiresPermissions("activity:getActivityTemplateDetails")
    public CommonResult getActivityTemplateDetails(@PathVariable String id) {
        ActivityTemplateDTO dto = spikeActivityService.getActivityTemplateDetails(id);
        return Ref.ok(dto);
    }

    @GetMapping("queryActivityTemplateList")
    @ApiOperation("整点抢购模板列表")
    @RequiresPermissions("activity:queryActivityTemplateList")
    public CommonResult queryActivityTemplateList(PageDTO pageDTO) {
        PageUtils page = spikeActivityService.queryActivityTemplateList(pageDTO);
        return Ref.ok(page);
    }

    @SysLog("修改整点抢购模板")
    @PostMapping("modifyActivityTemplateById")
    @ApiOperation("修改整点抢购模板")
    @RequiresPermissions("activity:modifyActivityTemplateById")
    public CommonResult modifyActivityTemplateById(@RequestBody ActivityTemplateDTO activityTemplateDTO) {
        spikeActivityService.modifyActivityTemplateById(activityTemplateDTO);
        return Ref.ok();
    }

    @SysLog("删除整点抢购")
    @ApiOperation("删除整点抢购")
    @PostMapping("removeActivityTemplate")
    @RequiresPermissions("activity:removeActivityTemplate")
    public CommonResult removeActivityTemplate(@RequestBody String[] ids) {
        spikeActivityService.removeActivityTemplate(Arrays.asList(ids));
        return Ref.ok();
    }
}
